package com.youfang.sixthmedia.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.util.Log;
import android.view.View;
import android.widget.BaseAdapter;
import ch.boye.httpclientandroidlib.HttpResponse;
import ch.boye.httpclientandroidlib.client.HttpClient;
import ch.boye.httpclientandroidlib.client.methods.HttpGet;
import ch.boye.httpclientandroidlib.util.EntityUtils;

import com.gzit.utils.MD5;
import com.youfang.sixthmedia.common.YoufangContext;
import com.youfang.sixthmedia.message.model.DetailBuilding.PhotoItem;
import com.youfang.sixthmedia.net.HttpRemoter;

public class PhotoController extends Thread {

	private static final String TAG = "PhotoController";

	private BlockingQueue<PhotoItem> downloadQueue = new LinkedBlockingQueue<PhotoItem>();

	private BaseAdapter adapter;
	private View view;

	private boolean running = true;

	// ///////////Cache部分//////////////
	public static class Cache {
		private static String photoCachePath = YoufangContext.APP_DIR + "photo"
				+ File.separator;

		static {
			ensureCachePath();
		}

		private static void ensureCachePath() {
			File file = new File(photoCachePath);
			if (!file.exists()) {
				file.mkdirs();
			}
		}

		public static void clearCache() throws IOException {
			FileUtils.cleanDirectory(new File(photoCachePath));
		}

		public static Bitmap getFromCache(String url) throws Exception {
			String logo = photoCachePath + MD5.toMD5(url);
			File logoFile = new File(logo);
			if (!logoFile.exists()) {
				return null;
			}
			return BitmapFactory.decodeFile(logo);

		}

		public static Uri getFromCacheURI(String url) throws Exception {
			String logo = photoCachePath + MD5.toMD5(url);
			File logoFile = new File(logo);
			if (!logoFile.exists()) {
				return null;
			}
			return Uri.fromFile(logoFile);
		}

		private static Uri cache(PhotoItem item, InputStream is)
				throws Exception {
			// 将数据保存到缓存目录下
			File logoFile = new File(photoCachePath + MD5.toMD5(item.url));
			
			//TC:FileOutputStream是否需要关闭
			IOUtils.copy(is, new FileOutputStream(logoFile));

			return Uri.fromFile(logoFile);
		}

		// /////////////////////////////////////////////////
	}

	public PhotoController() {
		this.setName("PhotoController");
		this.start();

	}

	public void setup(View view, BaseAdapter adapter) {
		this.adapter = adapter;
		this.view = view;
	}

	// 通知图标已就绪
	public void notifyLogoReady(PhotoItem b) {

		view.post(new Runnable() {
			@Override
			public void run() {
				adapter.notifyDataSetChanged();

			}
		});

	}

	private void doDownload(PhotoItem item) {

		HttpClient client = HttpRemoter.getYoufangRemoter().getHttpClient();
		try {

			
			URI logoURI = new URI(item.url);
			HttpGet get = new HttpGet(logoURI);
			HttpResponse resp = client.execute(get);
			int statusCode = resp.getStatusLine().getStatusCode();
			if (statusCode != 200) {
				Log.d(TAG, " download failed!statuscode:" + statusCode + ":"
						+ item.url);
				return;
			}

			// 缓存图标(InputStream是否需要关闭)
			item.localURI = Cache.cache(item, resp.getEntity().getContent());

			// 通知logo已下载
			notifyLogoReady(item);

			Log.d(TAG, "logo download ok:" + item.url);

		} catch (Exception e) {
			e.printStackTrace();
			Log.d(TAG,
					"logo download failed:" + item.url + "message:"
							+ e.getMessage());

			return;

		}

	}

	public void run() {
		while (running) {
			PhotoItem b;
			try {
				b = downloadQueue.take();
				doDownload(b);
				if (this.isInterrupted()) {
					return;
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
				running = false;
			}

		}

		Log.i(TAG, "PhotoController Thread stopped!");

	}

	// 在刷新时候调用
	public void onRefresh(List<PhotoItem> items) {

		Log.i(TAG, "PhotoController onRefresh!");
		this.downloadQueue.clear();

		for (PhotoItem item : items) {
			if (item.localURI == null) {
				this.downloadQueue.offer(item);
			}
		}

	}

	// 在activity停止的时候调用该方法停止logo的处理
	public void onStop() {

		Log.i(TAG, "PhotoController OnStop!");

		this.running = false;
		this.interrupt();
		this.downloadQueue.clear();

	}

	public void onDestroy() {
		Log.i(TAG, "PhotoController onDestroy!");

	}

}
